//
//  ViewController.m
//  iXorsPattern
//
//  Created by Dmitry Tatarinov on 1/30/15.
//  Copyright (c) 2015 Huly-Gun Soft. All rights reserved.
//


#import "stage.h"
#import "mainmenu.h"
#import "MoreGamesViewController.h"

//=========================================

@interface ViewController ()

@end


@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self authenticateLocalPlayer];
    _achievementsDictionary = [[NSMutableDictionary alloc] init];
    
    int orientation;
    #if TARGET_IPHONE_SIMULATOR
        orientation = 3;
    #else
        orientation = 2;
    #endif
    
    xGraphics3D(orientation, true, [[UIApplication sharedApplication] keyWindow]);
    MenuStage *stage = new MenuStage();
    stage->Load();
    stage->controller = self;
    //controller = self;
    
    animationInterval = 1.0 / 60.0;
    [self startAnimation];
    
    [self setupInterface];
    
    //[[MKStoreKit sharedKit] startProductRequest];
    //[[MKStoreKit sharedKit] availableProducts];
}

//===========================================================================================
#pragma mark setup Interface

- (void)setupInterface
{
    _moreGamesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_moreGamesBtn setTitle:@"More Games" forState:UIControlStateNormal];
    [_moreGamesBtn setFrame:CGRectMake(20, 20, 128, 64)];
    [_moreGamesBtn addTarget:self action:@selector(showMoreGames) forControlEvents:UIControlEventTouchUpInside];
    [xGetViewController().view addSubview:_moreGamesBtn];
}

- (void)showMoreGames
{
    MoreGamesViewController *vc = [[MoreGamesViewController alloc] init];
    [xGetViewController() presentViewController:vc animated:false completion:nil];
}

//===========================================================================================
#pragma mark Game Center

- (void)authenticateLocalPlayer
{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    
    localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
        if (viewController != nil) {
            [xGetViewController() presentViewController:viewController animated:YES completion:nil];
        }
        else {
            if ([GKLocalPlayer localPlayer].authenticated) {
                NSLog(@"GC enabled");
                //[self showGameCenter];
                //[self showLeaderboardAndAchievements:false];
            }
            else {
                NSLog(@"GC disabled");
            }
        }
    };
}

- (void)showGameCenter
{
    GKGameCenterViewController *gameCenterController = [[GKGameCenterViewController alloc] init];
    
    if (gameCenterController != nil)
    {
        gameCenterController.gameCenterDelegate = self;
        
        [xGetViewController() presentViewController: gameCenterController animated: YES completion:nil];
    }
}

- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
{
    [xGetViewController() dismissViewControllerAnimated:YES completion:nil];
}

- (void)showLeaderboardAndAchievements:(BOOL)shouldShowLeaderboard
{
    GKGameCenterViewController *gcViewController = [[GKGameCenterViewController alloc] init];
    
    gcViewController.gameCenterDelegate = self;
    
    if (shouldShowLeaderboard) {
        gcViewController.viewState = GKGameCenterViewControllerStateLeaderboards;
       // gcViewController.leaderboardIdentifier = leaderboardIdentifier;
    }
    else{
        gcViewController.viewState = GKGameCenterViewControllerStateAchievements;
    }
    
    [xGetViewController() presentViewController:gcViewController animated:YES completion:nil];
}

- (void)reportScore: (int) curScore lbIdentifier: (NSString *)leaderboardIdentifier
{
    GKScore *score = [[GKScore alloc] initWithLeaderboardIdentifier:leaderboardIdentifier];
    score.value = curScore;
    
    [GKScore reportScores:@[score] withCompletionHandler:^(NSError *error) {
        if (error != nil) {
            NSLog(@"%@", [error localizedDescription]);
        }
    }];
}

- (void) reportAchievementIdentifier: (NSString*) identifier percentComplete: (float) percent
{
    GKAchievement *achievement = [self getAchievementForIdentifier:identifier];
    
    if (achievement)
    {
        achievement.percentComplete = percent;
        
        [achievement reportAchievementWithCompletionHandler:^(NSError *error)
        {
             if (error != nil)
             {
                 // Log the error.
             }
         }];
    }
}

- (void) loadAchievements
{
    [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error)
    {
         if (error == nil)
         {
             for (GKAchievement* achievement in achievements)
                 [_achievementsDictionary setObject: achievement forKey: achievement.identifier];
         }
     }];
}

- (GKAchievement*) getAchievementForIdentifier: (NSString*) identifier
{
    GKAchievement *achievement = [_achievementsDictionary objectForKey:identifier];
    
    if (achievement == nil)
    {
        achievement = [[GKAchievement alloc] initWithIdentifier:identifier];
        [_achievementsDictionary setObject:achievement forKey:achievement.identifier];
    }
    
    return achievement;
}

- (void)showBanner
{
    NSString* title = @"Title";
    
    NSString* message = @"Message";
    
    [GKNotificationBanner showBannerWithTitle: title message: message
     
                            completionHandler:^{
                                
                                //[self advanceToNextInterfaceScreen]
                                
                            }];
}

//===========================================================================================
#pragma mark view main functions

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
//{
   // return (interfaceOrientation == UIInterfaceOrientationLandscapeRight);
//}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

//
#pragma mark iXors animation and draw

- (void)drawView
{
    if (!global_pause)
    {
        // check stage
        if(Stage::GetActive() == NULL) return;
        // update stage
        Stage::GetActive()->Update();
        // render stage
        Stage::GetActive()->Render();
    }
}

- (void)layoutSubviews
{
    xResetGraphics();
    [self drawView];
}

- (void)startAnimation
{
   animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(drawView) userInfo:nil repeats:YES];
}

- (void)stopAnimation
{
    animationTimer = nil;
}


@end
